package com.yicong.ants.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.yicong.ants.R;

public class TaskProgressView extends FrameLayout {
    LinearLayout progressItemLl;
    ProgressBar mProgressBar;

    public TaskProgressView(@NonNull Context context) {
        super(context);
        init();
    }

    public TaskProgressView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public TaskProgressView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public TaskProgressView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    private void init() {
        LayoutInflater.from(getContext()).inflate(R.layout.task_progress, this);
        progressItemLl = findViewById(R.id.progressItemLl);
        mProgressBar = findViewById(R.id.progressBar);
    }


    private void addSpace() {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, 0);
        params.weight = 1;
        progressItemLl.addView(new View(getContext()), params);
    }

    public void setCurrent(int current, int total) {
        if (current == total) {
            mProgressBar.setProgress(100);
        } else {
            mProgressBar.setProgress((int) (100f / 8 * current));
        }
        progressItemLl.removeAllViews();
        for (int i = 1; i <= total; i++) {
            addSpace();
            View progressItem = LayoutInflater.from(getContext()).inflate(R.layout.task_progress_item, null, false);
            if (i <= current) {
                TextView completionTimeTv = (TextView) progressItem.findViewById(R.id.completionTimeTv);
                completionTimeTv.setVisibility(View.VISIBLE);
                completionTimeTv.setText(i + "次");
                progressItem.setSelected(true);
            } else {
                TextView timeTv = (TextView) progressItem.findViewById(R.id.timeTv);
                timeTv.setVisibility(View.VISIBLE);
                timeTv.setText(i + "次");
            }
            if (i == total) {
                progressItem.findViewById(R.id.finalTaskIv).setVisibility(View.VISIBLE);
            }
            progressItemLl.addView(progressItem);
        }
        addSpace();
    }
}
